package info.mhylle.mediaplayer.playlist;

import helliker.id3.ID3v2FormatException;
import helliker.id3.MP3File;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.Scope;

import javax.media.*;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;


@Scope(org.jboss.seam.ScopeType.SESSION)
@Name("mediaplayer")
public class MediaPlayer implements ControllerListener {
    private String song;
    private Player player = null;

    private boolean shuffle = false;
    private boolean repeat = false;
    private Playlist playlist;

    MusicList musicList;


    public MediaPlayer() {
        System.out.println("new mediaplayer");
    }

    public MediaPlayer(MusicList musicList) {
        System.out.println("new mediaplayer2");
        this.musicList = musicList;
        playlist = new Playlist();
    }

    public String getSong() {
        return song;
    }

    public void setSong(String song) {
        this.song = song;
    }

    public void playSong(String filename) {
        System.out.println("filename = " + filename);
        song = filename;
        play();
    }

    public String addToPlayList(String album, String artist) {
        System.out.println("add to playlist");
        if (musicList != null) {
            System.out.println("found musiclist");
            List<MP3File> files = musicList.getSongsByAlbum(album, artist);
            System.out.println("files = " + files.size());
            for (MP3File file : files) {
                playlist.addMp3(file);
            }
            return "playlistcreated";
        }
        return "";
    }

    public void play() {

        MP3File mp3File;
        int position = playlist.getPosition();
        if (position < 0) {
            return;
        }
        mp3File = playlist.getList().get(position);


        File uFile;
        URL url = null;
        try {
            if (mp3File == null) {
                uFile = new File(song);
                url = uFile.toURL();
            } else {
                url = new File(mp3File.getPath()).toURL();
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
        if (player == null) {
            try {

                MediaLocator mediaLocator = new MediaLocator(url);
                player = Manager.createPlayer(mediaLocator);
                player.addControllerListener(this);
                player.realize();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (NoPlayerException e) {
                e.printStackTrace();
            }

        } else {
            player.start();

        }
    }

    public void playPlaylist() {
        MP3File mp3File = null;
        Settings.loadSettings();

        int position = Settings.getPlaylistPosition();

        mp3File = playlist.getList().get(position);

        if (player == null) {
            try {
                File file = new File(mp3File.getPath());
                MediaLocator mediaLocator = new MediaLocator(file.toURL());
                player = Manager.createPlayer(mediaLocator);
                player.addControllerListener(this);

                player.realize();
            }
            catch (MalformedURLException ex) {

            }
            catch (NoPlayerException ex) {

            }
            catch (IOException ex) {

            }
        } else {
            player.start();
        }
    }

    public void pause() {
        if (player != null) {
//            MP3File mp3File = null;
//            int position = playlist.getPosition();
//            mp3File = playlist.getList().get(position);
            player.stop();
        }
    }

    public void stop() {
        if (player != null) {
            player.removeControllerListener(this);
            player.stop();
            player.close();
            player = null;
        }
    }

    public void previous() {
        int position = playlist.getPosition();
        position--;
        if (position < 0) {
            position = 0;
        }
        playlist.setPosition(position);
        if (player != null) {
            stop();
        }
        play();
    }

    public void next() {
        int position;
        if (shuffle) {
            position = playlist.getRandomPosition();
        } else {
            position = playlist.getPosition();
            position++;
        }
        if (position >= playlist.getList().size()) {
            position = 0;
            playlist.setPosition(position);
            if (!repeat) {
                stop();
                return;
            }
        }
        playlist.setPosition(position);
        if (player != null) {
            stop();
        }
        play();
    }

    public void controllerUpdate(ControllerEvent ev) {
        if (ev instanceof RealizeCompleteEvent) {
            player.prefetch();
        }
        if (ev instanceof PrefetchCompleteEvent) {
            player.getGainControl().setLevel(1);
            player.start();
        }
        if (ev instanceof EndOfMediaEvent) {
//            player.removeControllerListener(this);
//            player.stop();
//            player.close();
//            player = null;
            next();
        }
    }

    public boolean playing(String artist, String title) {
        int position = Settings.getPlaylistPosition();
        MP3File mp3File = playlist.getList().get(position);
        try {
            if (mp3File.getArtist().equals(artist) && mp3File.getTitle().equals(title)) {
                return true;
            }
        } catch (ID3v2FormatException e) {
            e.printStackTrace();
        }
        return false;
    }

    public void setMusicList(MusicList musicList) {
        this.musicList = musicList;
    }

    public Playlist getPlaylist() {
        return playlist;
    }

    public void setPlaylist(Playlist playlist) {
        this.playlist = playlist;
    }


    /**
     * Shuffle does exactly that. It shuffles the playlist.
     * Shuffle will start the playlist from scratch.
     */
    public void shuffle() {
        shuffle = !shuffle;
    }
}
